package 优先算法.滑动窗口.水果成篮;

import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Solution2 so = new Solution2();
        int[] arr = {1,2,3,2,2};
        int rel = so.totalFruit(arr);
        System.out.println(rel);
    }
}
class Solution2 {
    public int totalFruit(int[] fruits) {
        int[] arr = new int[fruits.length+1];
        int left = 0,right = 0,len = 0,kind = 0;
        while(right < fruits.length){
            //进窗口
            int key = fruits[right++];
            if(arr[key] == 0){
                kind++;
            }
            arr[key]++;

            while(kind > 2){
                //出窗口
                int out = fruits[left++];
                arr[out]--;
                if(arr[out] == 0){
                    kind--;
                }
            }
            len = Math.max(len,right - left);
        }
        return len;
    }
}
class Solution {
    public int totalFruit(int[] fruits) {
        Map<Integer,Integer> map = new HashMap<Integer,Integer>();
        int left = 0,right = 0,len = 0;
        while(right < fruits.length){
            //进窗口
            int key = fruits[right++];
            map.put(key,map.getOrDefault(key,0)+1);

            while(map.size() > 2){
                //出窗口
                int out = fruits[left++];
                map.put(out,map.get(out)-1);
                if(map.get(out) == 0){
                    map.remove(out);
                }
            }
            len = Math.max(len,right - left);
        }
        return len;
    }
}